package com.kkb.mybatis.myTest;

import org.junit.Test;

import java.sql.*;

/**
 * 测试原生jdbc
 */
public class JdbcDemo {

    @Test
    public void test() {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet rs = null;
        try {
            // 1、加载数据库驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 2、通过驱动管理类获取数据库链接connection = DriverManager
            connection = DriverManager.getConnection(
                    "jdbc:mysql://192.168.10.215:3306/heixiniu_dev",
                    "xdd-dev",
                    "devHxn123!@#");

            // 3、定义sql语句 ?表示占位符
            String sql = "select * from dc_users where user_id IN(?,?,?)";

            // 4、获取预处理 statement
            preparedStatement = connection.prepareStatement(sql);

            // 5、设置参数，第一个参数为 sql 语句中参数的序号（从 1 开始），第二个参数为设置的
            preparedStatement.setObject(1, 4471);
            preparedStatement.setObject(2, 4472);
            preparedStatement.setObject(3, 4473);

            // 6、向数据库发出 sql 执行查询，查询出结果集
            rs = preparedStatement.executeQuery();

            // 7、遍历查询结果集
            while (rs.next()) {
                System.out.println(rs.getString("user_id") + " " + rs.getString("username") + " " + rs.getString("truename"));
            }

        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        } finally {
            // 8、释放资源
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }













    }

}
